﻿using System;
using System.IO;
using System.Text;
using WMSSyncData.Utils;

namespace SyncUserAccount
{
    class MyBll
    {
        public string DeleteUsers()
        {
            string msg = "";
            SqlDBHelper.Conn = "Data Source=192.168.9.75;Initial Catalog=WMS;User ID=WMS;Password=Password01!;";

            string sqlCmd = @"select u.UserID,u.UserName,ht.bh as HRID,ht.xm as HRName from SysDatUser u left join [HR_LINK_SN].[Amphenol].[dbo].[employee] ht
                            on u.UserID = ht.bh  collate Chinese_PRC_90_CI_AI
                            where ht.bh is null and UserID<> 'admin' ORDER BY UserID";
            var dt = SqlDBHelper.GetTable(sqlCmd.ToString());

            string delcmdAll = "";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string delCmd = "delete from SysDatUser where UserId='{0}';";
                delCmd = string.Format(delCmd, dt.Rows[i]["UserId"].ToString());
                msg = msg + dt.Rows[i]["UserId"].ToString() + "," + dt.Rows[i]["UserName"].ToString() + "\r\n";
                delcmdAll = delcmdAll + delCmd;
            }
            if (delcmdAll != "")
                SqlDBHelper.ExcuteSQL(delcmdAll);

            return msg;
        }

        private void WriteLine(string txtContent)
        {
            var FilePath = System.Configuration.ConfigurationManager.AppSettings["FilePath"];
            string fileName = FilePath + "UserCancel" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            if (File.Exists(fileName))
            {
                //读取文本
                StreamReader sr = File.OpenText(fileName);
                string input = sr.ReadToEnd();
                sr.Close();
                StreamWriter sw = new StreamWriter(fileName);
                sw.Write(input); //将原文本写入
                //sw.WriteLine();  //隔行
                sw.WriteLine(txtContent);  //txtcontent 是要写入的数据
                sw.Close();
            }
            else
            {
                FileStream fs = new FileStream(fileName, FileMode.CreateNew);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(txtContent);  //这里是写入的内容             
                sw.Flush();
                sw.Close();
            }
        }

        private string DeleteUser(string jobNo)
        {
            var entry = ADHelper.GetSAAEntry();
            var user = ADHelper.GetUserEntryByJobNo(entry, jobNo.ToLower());
            if (user != null)
            {
                string bkUser = "";
                foreach (var name in user.Properties.PropertyNames)
                {
                    var strPts = "";
                    object obj = user.Properties[name.ToString()].Value;
                    if (obj.GetType() == typeof(object[]))
                    {
                        object[] pts = (object[])obj;
                        foreach (var pt in pts)
                        {
                            strPts = strPts + pt + ";";
                        }
                    }
                    else
                    {
                        strPts = obj.ToString();
                    }

                    bkUser = bkUser + name + ":" + strPts + ",";
                }
                WriteLine(bkUser);
                user.DeleteTree();
                user.CommitChanges();
                user.Dispose();
                entry.Dispose();

                return "saa.com已清除用户" + jobNo + "\r\n";
            }
            else
            {
                //return "saa.com无此用户" + jobNo + "\r\n";
                return "";
            }
        }

        private string DeleteMCPUser(string jobNo)
        {
            var mcpEntry = ADHelper.GetMCPEntry();
            var mcpUser = ADHelper.GetUserEntry(mcpEntry, ("saa" + jobNo).ToLower());
            if (mcpUser != null)
            {
                string bkUser = "";
                foreach (var name in mcpUser.Properties.PropertyNames)
                {
                    var strPts = "";
                    object obj = mcpUser.Properties[name.ToString()].Value;
                    if (obj.GetType() == typeof(object[]))
                    {
                        object[] pts = (object[])obj;
                        foreach (var pt in pts)
                        {
                            strPts = strPts + pt + ";";
                        }
                    }
                    else
                    {
                        strPts = obj.ToString();
                    }

                    bkUser = bkUser + name + ":" + strPts + ",";
                }
                WriteLine(bkUser);
                mcpUser.DeleteTree();
                mcpUser.CommitChanges();
                mcpUser.Dispose();
                mcpEntry.Dispose();

                return "amphenolmcp.com已清除用户" + jobNo + "\r\n";
            }
            else
            {
                //return "amphenolmcp.com无此用户" + jobNo + "\r\n";
                return "";
            }
        }

        public string CancelSHUsers()
        {
            string SHBody = "";
            SHBody += DateTime.Now.ToString() + ":上海同步清除账号处理开始" + "\r\n";

            SqlDBHelper.Conn = "Data Source=192.168.0.11;Initial Catalog=Amphenol;User ID=moss;Password=Moss12345;";
            string sql = @"select * from [dbo].[hrinfor] where leavedateA = CONVERT(date,getdate()-1,112) and status<>1";
            //string sql = @"select * from [dbo].[hrinfor] where leavedateA >= 20200901 and leavedateA < 20201001 and status<>1";
            var dt = SqlDBHelper.GetTable(sql.ToString());

            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var jobNo = dt.Rows[i]["emid"].ToString();
                var name = dt.Rows[i]["namec"].ToString();
                var dept = dt.Rows[i]["dept"].ToString();
                var leaveDate = dt.Rows[i]["leavedateA"].ToString();

                SHBody += i.ToString() + "---工号:" + jobNo + ",姓名:" + name + ",部门:" + dept + ",离职日期:" + leaveDate + "\r\n";

                SqlDBHelper.Conn = "server=192.168.9.75;database=WMS;user id=WMS;Password=Password01!;";
                string delCmd = "delete from SysDatUser where UserId='{0}';";
                delCmd = string.Format(delCmd, jobNo);
                if (SqlDBHelper.ExcuteSQL(delCmd) > 0)
                {
                    SHBody += "WMS系统已清除用户" + jobNo + "\r\n";
                }
                else
                {
                    //SHBody += "WMS系统无此用户" + jobNo + "\r\n";
                }

                var str = DeleteUser(jobNo);
                SHBody += str;
                var str2 = DeleteMCPUser(jobNo);
                SHBody += str2;
            }
            if (dt.Rows.Count == 0)
            {
                SHBody += "前日无离职人员,无需处理" + "\r\n"; ;
            }
            SHBody += DateTime.Now.ToString() + ":上海同步清除账号处理结束" + "\r\n" + "\r\n";
            WriteLine(SHBody);
            return SHBody;
        }

        public string CancelHYUsers()
        {
            string HYBody = "";
            HYBody += DateTime.Now.ToString() + ":海盐同步清除账号处理开始" + "\r\n";

            SqlDBHelper.Conn = "Data Source=192.168.0.11;Initial Catalog=Amphenoltech;User ID=moss;Password=Moss12345;";
            string sql = @"select * from [dbo].[hrinfor] where leavedateA = CONVERT(date,getdate()-1,112) and status<>1";
            //string sql = @"select * from [dbo].[hrinfor] where leavedateA >= 20200901 and leavedateA < 20201001 and status<>1";
            var dt = SqlDBHelper.GetTable(sql.ToString());

            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var jobNo = dt.Rows[i]["emid"].ToString();
                var name = dt.Rows[i]["namec"].ToString();
                var dept = dt.Rows[i]["dept"].ToString();
                var leaveDate = dt.Rows[i]["leavedateA"].ToString();

                HYBody += i.ToString() + "---工号:" + jobNo + ",姓名:" + name + ",部门:" + dept + ",离职日期:" + leaveDate + "\r\n";

                SqlDBHelper.Conn = "server=192.168.9.75;database=WMS_105;user id=WMS105;Password=Password01!;";
                string delCmd = "delete from SysDatUser where UserId='{0}';";
                delCmd = string.Format(delCmd, jobNo);
                if (SqlDBHelper.ExcuteSQL(delCmd) > 0)
                {
                    HYBody += "WMS系统已清除用户" + jobNo + "\r\n";
                }
                else
                {
                    //HYBody += "WMS系统无此用户" + jobNo + "\r\n";
                }

                var str = DeleteUser(jobNo);
                HYBody += str;
                var str2 = DeleteMCPUser(jobNo);
                HYBody += str2;
            }
            if (dt.Rows.Count == 0)
            {
                HYBody += "前日无离职人员,无需处理" + "\r\n";
            }

            HYBody += DateTime.Now.ToString() + ":海盐同步清除账号处理结束" + "\r\n" + "\r\n";
            WriteLine(HYBody);
            return HYBody;
        }

        public void Send()
        {
            var str = CancelSHUsers();
            var str1 = CancelHYUsers();
            Do.SendMailsWithBody(str + str1);
        }
        //NEND

    }
}
